﻿using System;
using NHibernate;

namespace Common.Infrastructure.Persistence.Repositories
{
    public class GenericCrudRepository<T>
    {
        protected readonly ISession Session;

        public GenericCrudRepository(ISession session)
        {
            Session = session;
        }

        public virtual T Get(Guid id)
        {
            var result = Session.Get<T>(id);
            if(result == null)
                //todo: create a new exc class example (EntityNotFoundExc)
                throw new NullReferenceException("Object not found in db");
            return result;
        }

        public virtual void Update(T item)
        {
            Session.SaveOrUpdate(item);
        }

        public virtual void Add(T item)
        {
            Session.Save(item);
        }

        public virtual void Delete(T item)
        {
            Session.Delete(item);
        }
        
        public virtual void Delete(Guid id)
        {
            Delete(Session.Load<T>(id));
        }
    }
}
